package com.matrix.draft.sockettest.day10.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    // handlerAdded表示连接建立, 这个方法第一个执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        System.out.println("-----------  "+ctx.channel().remoteAddress()+"  -------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        // 读取
        byte[] bytes = new byte[msg.readableBytes()];
        msg.readBytes(bytes);
        System.out.println("Got from client : "+new String(bytes, StandardCharsets.UTF_8));
        // 回复
        ctx.writeAndFlush(Unpooled.copiedBuffer("REPLY ",StandardCharsets.UTF_8));
    }
}
